import Axios from 'axios';
import Qs from 'qs';
import Store from '@/stores/index';
import { common } from '@/utils';
import { i18n } from '@/locales';

export default class Service {
  constructor() {
    this.scmDomain = {
      TMS: '/SCM.TMS7.WebApi/',
      WMS: '/SCM.Customization/TwCarrefour.WebUI/api/App/',
    };
    this.$t = i18n.global.t;
    this.paramsSerializer = params => Qs.stringify(params, { indices: false });
    this.baseUrl = null;
    this.instance = Axios.create({
      timeout: 0,
      paramsSerializer: this.paramsSerializer,
    });
    this.instance.interceptors.request.use(
      config => {
        this.baseUrl = Store.getters['common/getData']({ key: 'baseUrl', modules: 'common' });
        config.baseURL = `${this.baseUrl + this.scmDomain[config.scm]}`;

        this.token = Store.getters['common/getData']({ key: 'token', modules: 'common' });

        if (config.isCheckToken) {
          if (this.token) {
            config[config.method === 'get' ? 'params' : 'data'].token = this.token;
          } else {
            common.noToken();
            Promise.reject(new Error(this.$t('noToken')));
          }
        }

        config.headers = {
          'Content-Type': config.formData
            ? 'application/x-www-form-urlencoded;charset=UTF-8'
            : 'application/json;charset=UTF-8',
        };

        return Promise.resolve(config);
      },
      error => Promise.reject(error),
    );
    this.instance.interceptors.response.use(
      response => {
        const { data } = response;
        if (data.resultCode === 2) {
          common.noToken();
        }
        return Promise.resolve(data);
      },
      error => {
        const code = parseInt(error.response.status, 10);
        const httpCode = {
          401: this.$t('401'),
          403: this.$t('403'),
          404: this.$t('404'),
          405: this.$t('405'),
          500: this.$t('500'),
          501: this.$t('501'),
          502: this.$t('502'),
          504: this.$t('504'),
        };
        this.notify({ message: httpCode[code] ?? this.$t('serverException'), code });
        return Promise.reject(error);
      },
    );
  }

  notify({ message = '', code = '' } = {}) {
    if (code === 401) {
      common.noToken();
    } else {
      i18n.$dialog.alert({
        message: `${message}`,
      });
    }
  }
}
